﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using umbraco;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Xml.Xsl;
using umbraco.IO;
using System.Net;
using System.Web.Caching;
using System.IO;
using umbraco.cms.businesslogic.macro;

namespace Core.Module.Controls
{
    public class RenderXslt: WebControl
    {
        public string XsltFile { get; set; }

        public Hashtable PageElements { get; set; }
        public MacroModel Model { get; set; }
        public bool CacheByPage { get; set; }
        public bool CacheByMember { get; set; }
        public int CacheDuration { get; set; }
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            macro m = new macro();
             
            m.Name = this.ID;
            m.Alias = "virtualmacro"+m.Name;
            m.MacroContent = "";
            m.MacroID = -99999;
            m.XsltFile = XsltFile;
            MacroModel model = LoadModel(m);
            foreach (string akey in this.Attributes.Keys)
            {
                string avalue=this.Attributes[akey];
                m.Properties.Add(akey, avalue);
                model.Properties.Add(new MacroPropertyModel(akey, avalue));
            }
            
            Control c = m.renderMacro(model, LoadPageElements(m),umbraco.presentation.UmbracoContext.Current.PageId.HasValue?umbraco.presentation.UmbracoContext.Current.PageId.Value:-1);
            c.RenderControl(writer);
        }

        private Hashtable LoadPageElements(macro m)
        {
            Hashtable res = PageElements;
            if (res == null) res = new Hashtable();
            //fill page elements                        
            return res;
        }

        private MacroModel LoadModel(macro m)
        {
            if (Model != null) return Model;
            MacroModel res = new MacroModel(
                    m.Name,
                    m.Alias,
                    string.Empty,
                    string.Empty,
                    m.XsltFile,
                    string.Empty,
                    CacheDuration,
                    CacheByPage,
                    CacheByMember
                );
            
            return res;
        }


    }
}
